package ll.timer
{
	import flash.utils.getTimer;

	public class FrameThread
{
	/** 速度，等待多少帧执行一次 */
	public var delay:int;
	/** 等待计数 */
	public var counter:int;
	/** 重复次数，0为无限次 */
	public var repeat:int;
	/** 回调函数 */
	public var closure:Function;
	/** 回传参数 */
	public var parameters:*;
	/** 帧频 */
	public var frameRate:int;
	/** 上次调用时间 */
	public var lastTime:int;
	
	public function FrameThread(delay:int, repeat:int, callback:Function, frameRate:int = -1, ...parameters)
	{
		this.delay = delay;
		this.counter = delay * FrameTimer.STAGE_FRAME_RATE / (frameRate == -1 ? FrameTimer.DEFAULT_FRAME_RATE : frameRate);
		this.repeat = repeat;
		this.closure = callback;
		this.parameters = parameters;
		this.frameRate = frameRate;
		this.lastTime = getTimer();
	}
	
	/** 
	 * 执行
	 * @param	time	当前时间（getTimer）
	 * @param	d_t		与上次执行的间隔
	 * @return	Boolean	true表示有执行，false表示没有达到执行条件
	 */ 
	public function exec(time:int, d_t:int):Boolean
	{
		var trate:int = frameRate == -1 ? FrameTimer.DEFAULT_FRAME_RATE : frameRate;
		var tinv:int = 1000 / trate;
		var tdelay:int = delay * FrameTimer.STAGE_FRAME_RATE / trate;
		var td_t:int = time - lastTime;
		if(td_t >= tinv * tdelay || (--counter < 1))
		{
			lastTime = time;
			counter = tdelay;
			closure.call(null, parameters);
			return true;
		}
		
		return false;
	}
}
}